##########################################
## Copyright 2012-2013 Ceruti Francesco
##
##
## This file is part of LiSP (Linux Show Player).
##
## LiSP (Linux Show Player) is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## LiSP (Linux Show Player) is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with LiSP (Linux Show Player).  If not, see <http://www.gnu.org/licenses/>.
##########################################

import urllib.request as url
from ast import literal_eval

try:
    from lxml import etree
except ImportError:
    import xml.etree.ElementTree as etree


class InvalidTag(Exception):
    pass


class XmlReader:

    tag = {
           'medialist': 0,
           'program': 1,
           'plugins': 2
           }

    def __init__(self, file):
        parser = etree.XMLParser(remove_blank_text=True)
        self.root = etree.parse(file, parser).getroot()

    def readMedia(self, media):
        conf = {}
        for opt in media:
            conf[opt.attrib['name']] = literal_eval(url.url2pathname(opt.attrib['value']))
        return conf

    def readMediaList(self):
        medialist = []
        for media in self.root[self.tag['medialist']]:
            medialist.append(self.readMedia(media))
        return medialist

    def readPluginSettings(self, plugin):
        conf = {}
        for opt in plugin:
            conf[opt.attrib['name']] = literal_eval(url.url2pathname(opt.attrib['value']))
        return conf

    def readPluginsSettings(self):
        plugins = {}
        for plugin in self.root[self.tag['plugins']]:
            plug = plugin.attrib['name']
            plugins[plug] = self.readPluginSettings(plugin)
        return plugins

    def readProgramSettings(self):
        settings = {}
        for opt in self.root[self.tag['program']]:
            settings[opt.attrib['name']] = literal_eval(url.url2pathname(opt.attrib['value']))
        return settings
